/**
 * @file form reducer
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import {
  // 其他 Action
  REQ_ACTION,
  REC_ACTION,
  REQ_FETCH_DATA,
  REC_FETCH_DATA,
  REQ_FETCH_SCHEMA,
  REC_FETCH_SCHEMA,

  RESET_DATA
} from './action-types';
import {handleActions} from 'redux-actions';
import * as update from 'react-addons-update';
import {createRequestReducer, createReceiveReducer, compose} from '../renderer';

export default handleActions({

  // 获取数据相关
  [REQ_FETCH_DATA]: createRequestReducer(),
  [REC_FETCH_DATA]: compose((state, action) => action.error ? state : update(state, {
    data: {
      [state.data ? '$merge' : '$set']: action.payload.data
    }
  }), createReceiveReducer()),

  // 单条操作
  [REQ_ACTION]: createRequestReducer('saving', 'action'),
  [REC_ACTION]: compose((state, action) => update(state, {
    reloadFlag: {
      $set: true // 标记失效, 需要重新刷新
    }
  }), createReceiveReducer('saving', 'action')),

  // schema
  [REQ_FETCH_SCHEMA]: createRequestReducer('fetching', 'schema'),
  [REC_FETCH_SCHEMA]: compose((state, action) => action.error ? state : update(state, {
    schema: {
      data: {
        [state.schema.data ? '$merge' : '$set']: action.payload.data
      }
    }
  }), createReceiveReducer('fetching', 'schema')),

  [RESET_DATA]: (state, action) => update(state, {
    data: {
      $set: action.payload || null
    }
  })

// initState
}, {
  ctx: null,
  message: null,
  error: null,
  invalid: false,
  fetching: false,
  saving: false,
  data: null,
  reloadFlag: false,

  action: {
    ctx: null,
    message: null,
    saving: false,
    invalid: false,
    error: null
  },

  schema: {
    data: null,
    ctx: null,
    message: null,
    fetching: false,
    invalid: false,
    error: null
  }
});